package com.lagou.ipersistence.parsing;

/**
 * 通用标志解析器
 * 只能处理一个
 *
 * @author Yan Jiahong
 * Created on 2020/11/15
 */
public class GenericTokenParser {
    private final String openToken;
    private final String closeToken;
    private final TokenHandler handler;

    public GenericTokenParser(String openToken, String closeToken, TokenHandler handler) {
        this.openToken = openToken;
        this.closeToken = closeToken;
        this.handler = handler;
    }

    public String parse(String text) {
        if (text == null || text.length() == 0) {
            return "";
        }
        int start = text.indexOf(openToken);
        if (start == -1) {
            return text;
        }

        char[] src = text.toCharArray();
        StringBuilder expression = null;
        int offset = 0;
        StringBuilder builder = new StringBuilder();
        while (start > -1) {
            // 初始化或者重置表达式建造器
            if (expression == null) {
                expression = new StringBuilder();
            } else {
                expression.setLength(0);
            }
            // 拍新意位置
            builder.append(src, offset, start - offset);
            offset = start + openToken.length();
            int end = text.indexOf(closeToken, offset);
            if (end == -1) {
                // 没有找关闭标志
                builder.append(src, start, src.length - start);
                offset = src.length;
            } else {
                // 找到了关闭标志
                expression.append(src, offset, end - offset);
                builder.append(handler.handle(expression.toString()));
                offset = end + closeToken.length();
            }
            // 计算start位置
            start = text.indexOf(openToken, offset);
        }

        // 拼接剩余部分
        if (offset < src.length) {
            builder.append(src, offset, src.length - offset);
        }
        return builder.toString();
    }
}
